import requests
import re
class BaiduTranslation:
    def __init__(self):
        pass
    def search(self,word):
        resp = {'code': 200, 'msg': "翻译成功", "data":{}}
        # 请求百度搜索
        headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
                   'Accept - Encoding': 'gzip, deflate, br',
                   'Accept-Language': 'zh-Hans-CN, zh-Hans; q=0.5',
                   'Connection': 'Keep-Alive',
                   'Host': 'www.baidu.com',
                   'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Edge/15.15063'}

        req = requests.get("http://www.baidu.com/s?ie=utf-8&word=%s" % word, headers=headers).text
        req = req.replace(" ", "").replace("\n", "")
        #print(req)
        # 匹配单词
        pattern = re.compile(r'<tdclass="op_dict3_englishtxtc-color-t"><spanclass="op_dict3_font24op_dict3_marginRight">(.*?)</span></td>',re.M)
        res = pattern.search(req)
        if res and res.group(1) == word:
            #匹配英标
            pattern = re.compile(r'<spanclass="op_dict3_font16op_dict3_gap_small">(.*?)</span>', re.M)
            res = pattern.findall(req)
            if len(res) < 1:
                resp['code'] = -1
                resp['msg'] = "获取音标失败"
                return resp
            phonetic = res[0]
            resp['data']['phonetic'] = phonetic
            # 匹配词性和中文
            pattern = re.compile(r'<tableborder="0"cellspacing="0"cellpadding="0"class="op_dict3_english_result_table"><tr><td><spanclass="op_dict_text1op-dict3-grayc-gap-right">(.*?)</span></td><td><spanclass="op_dict_text2">(.*?)</span></td></tr></table>', re.M)
            res = pattern.findall(req)
            if len(res) < 1:
                resp['code'] = -1
                resp['msg'] = "获取词性和中文失败"
                return resp
            resp['data']['translation'] = []
            for i in res:
                tmp = {'class': i[0], 'ch': i[1]}
                resp['data']['translation'].append(tmp)
            # 添加发音
            resp['data']['pronounce'] = self.getTtsUrl(word)
        else:
            resp['msg'] = "百度翻译没有该数据"
            resp['code'] = -1
            return resp
        return resp
    def getTtsUrl(self,word):
        return "https://sp0.baidu.com/-rM1hT4a2gU2pMbgoY3K/gettts?lan=en&text=%s&spd=2&source=alading" % word






if __name__ == "__main__":
    bd = BaiduTranslation()
    res = bd.search("where")
    print(res)